/*
Source : https://leetcode.com/problems/palindrome-linked-list/
Author : nflush@outlook.com
Date   : 2016-07-04
*/

/*
234. Palindrome Linked List
Total Accepted: 54602 Total Submissions: 187414 Difficulty: Easy

Given a singly linked list, determine if it is a palindrome.

Follow up:
Could you do it in O(n) time and O(1) space?

Subscribe to see which companies asked this question

*/

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    bool isPalindrome(ListNode* head) {
        if (!head || !head->next){
            return true;
        }
        ListNode *p1 = head;
        ListNode *p2 = head;
        ListNode *rev = head;
        ListNode *pre = NULL;
        while (p2 && p2->next){
            p2 = p2->next->next;
            p1 = p1->next;
            rev->next = pre;
            pre = rev;
            rev = p1;
        }
        if (p2){
            p1 = p1->next;
        }
        while(pre != NULL){
            if (pre->val != p1->val){
                return false;
            }
            pre = pre->next;
            p1 = p1->next;
        }
        return true;
    }
};

